//
//  Button.swift
//  Jock
//
//  Created by HD on 15/4/4.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

class Button: UIView {
    
    var normalColor: UIColor!
    var pressColor: UIColor!
    
    private var tapEnd = true
    private var click: ((Button) -> Void)!

    override init(frame: CGRect) {
        super.init(frame: frame)
        initColor()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initColor()
    }
    
    func click(click: (button: Button) -> Void) {
        self.click = click
    }

    // 初始化背景色
    private func initColor() {
        normalColor = UIColor(red: 0xee / 255, green: 0xee / 255, blue: 0xee / 255, alpha: 1)
        pressColor = UIColor(red: 0xcc / 255, green: 0xcc / 255, blue: 0xcc / 255, alpha: 1)
        self.backgroundColor = normalColor
    }
    
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        if let press = pressColor {
            self.backgroundColor = press
        }
        tapEnd = false
    }
    
    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
        super.touchesMoved(touches, withEvent: event)
        let point = (touches.first as! UITouch).locationInView(self)
        if tapEnd || point.x < 0 || point.y < 0 || point.x > frame.width || point.y > frame.height {
            tapEnd = true
            self.touchesEnded(touches, withEvent: event)
        }
    }
    
    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        if let normal = normalColor {
            if self.backgroundColor != normalColor {
                self.backgroundColor = normal
                if !tapEnd && click != nil {
                    click(self)
                }
            }
        }
        tapEnd = true
    }

}
